package com.baili.app.ycbl.plugin.gensee

import android.app.Activity
import android.util.Log
import com.gensee.common.ServiceType
import com.gensee.entity.InitParam
import com.gensee.fastsdk.GenseeLive
import com.gensee.fastsdk.core.GSFastConfig
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

class GenseeMethodCallImpl (private val activity: Activity): MethodChannel.MethodCallHandler {


    /** flutter 调用 Android 方法*/
    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        //获取传入的参数
        val liveParams = parseParams(call, result) ?: return

        when(call.method) {
            "startLive" -> startLive(liveParams, result)
            "startVod" -> startVod(liveParams, result)
            else -> result.notImplemented()
        }
    }

    /**
     * 进入直播
     */
    private fun startLive(initParam: InitParam, result: MethodChannel.Result) {
        log("进入直播")
        GenseeLive.startLive(activity, GSFastConfig(), initParam)
        // 回复通信，Flutter 端不需要结果，则可以不写
        result.success(true)
    }

    /**
     * 进入回放
     */
    private fun startVod(initParam: InitParam, result: MethodChannel.Result) {
        log("进入回放")
        GenseeLive.startVod(activity, initParam, GSFastConfig())
        // 回复通信，Flutter 端不需要结果，则可以不写
        result.success(true)
    }


    /**
     * 解析传入的参数
     */
    private fun parseParams(call: MethodCall, result: MethodChannel.Result): InitParam? {


        val roomNum: String? = call.argument("roomNumber")
        val joinPassword: String? = call.argument("joinPassword")
        val userName: String? = call.argument("userName")

        if (roomNum.isNullOrEmpty()) {
            resultError("房间号不能为空", result)
            return null
        }
        if (joinPassword.isNullOrEmpty()) {
            resultError("密码不能为空", result)
            return null
        }
        if (userName.isNullOrEmpty()) {
            resultError("用户名不能为空", result)
            return null
        }

        log("roomNumber: $roomNum ; joinPassword: $joinPassword ; userName: $userName")

        return initParam(roomNum, joinPassword, userName)
    }

    /**
     * 获取初始化参数
     */
    private fun initParam(roomNum: String, joinPassword: String, userName: String) = InitParam().apply {
        //域名
        domain = "bailiedu.gensee.com"
        //房间号
        number = roomNum
        //加入密码
        joinPwd = joinPassword
        //昵称 昵称需要写活
        nickName = userName
        //站点类型
        serviceType = ServiceType.TRAINING

    }

    private fun resultError(errMsg: String, result: MethodChannel.Result) {
        result.error("404", errMsg, "缺失必要参数")
    }

    private fun log(msg: Any?) {
        Log.d("GenseeMethodCallImpl", "$msg")
    }
}